package dsf.eshop.user.web;

import dsf.eshop.commons.base.BaseResult;
import dsf.eshop.commons.utils.CaptchaUtil;
import dsf.eshop.commons.utils.RandomUtil;
import dsf.eshop.user.entity.User;
import dsf.eshop.user.service.UserService;
import dsf.eshop.user.utils.MailUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresGuest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class HomeController {

    @Autowired
    private MailUtil mailUtil;

    @Resource
    private UserService userService;

    @ApiOperation("默认界面")
    @GetMapping("/index")
    public String index() {
        return "index";
    }

    @ApiOperation("登录html页面")
    @GetMapping("/login")
    public String login() {
        return "user/login";
    }

    @ApiOperation("登录接口")
    @PostMapping("/login")
    public String login(HttpServletRequest request, Map<String, String> map) {

        log.info("HomeController.login()");
        // 登录失败从request中获取shiro处理的异常信息。
        // shiroLoginFailure:就是shiro异常类的全类名.
        String exception = (String) request.getAttribute("shiroLoginFailure");
        log.info("exception=" + exception);
        String msg = "";
        if (exception != null) {
            if (UnknownAccountException.class.getName().equals(exception)) {
                msg = "账号不存在";
            } else if (IncorrectCredentialsException.class.getName().equals(exception)) {
                msg = "密码不正确：";
            } else if ("kaptchaValidateFailed".equals(exception)) {
                msg = "验证码错误";
            } else {
                log.error(exception);
                msg = "意料之外的错误";
            }
            log.error("登录失败 {}", msg);
        }
        map.put("msg", msg);
        // 此方法不处理登录成功,由shiro进行处理
        return "user/login";
    }

    @PostMapping("/logout")
    public String logout(HttpServletRequest request) {

        request.getSession().removeAttribute("phone");
        return "redirect:index";

    }

    @GetMapping("/403")
    public String e403() {
        return "403";
    }

    @GetMapping("/home/captcha")
    public void captcha(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {


        HashMap<String, Object> hashMap = CaptchaUtil.create(80, 39, 4);
        log.info(">>>>>enter captcha");
        BufferedImage captchaImage = (BufferedImage) hashMap.get("captchaImage");
//        log.info(">>>>>>>>>{}", captchaImage);
        File file = new File("test");
        if(!file.exists()) {
            file.createNewFile();
        }
        ImageIO.write(captchaImage, "JPEG", httpResponse.getOutputStream());
        httpRequest.getSession().setAttribute("captchaCode", hashMap.get("captchaCode"));

        log.info(">>>>>>>>>>>>>>>>>>>>> captchaCode {}", hashMap.get("captchaCode"));
    }


    @GetMapping("/register")
    public String register() {

        return "user/register";
    }

    @GetMapping("/home/verifyCode")
    @ResponseBody
    public void verifyCode(String email, HttpServletRequest request) {

        Date date = new Date();
        if(null == email) {
            return;
        }
        String verifyCode = RandomUtil.randomString(6);
        request.getSession().setAttribute("verifyCode", verifyCode);
        request.getSession().setAttribute("verifyEmail", email);
        mailUtil.postMail(email, "注册验证码", verifyCode);
        log.info("发邮件消耗时间{}", (new Date()).getTime()-date.getTime());
    }

    @PostMapping("/register")
    @ResponseBody
    public BaseResult register(String emailCode, String captchaCode, User user, HttpServletRequest request) {

        HttpSession session = request.getSession();
        String captchaCode1 = (String) session.getAttribute("captchaCode");

        log.info("输入验证码{} 正确验证码{}", captchaCode, captchaCode1);
        if(captchaCode == null || !captchaCode.toLowerCase().equals(captchaCode1.toLowerCase())) {
            return new BaseResult(1, "验证码错误");
        }

        String verifyCode = (String) session.getAttribute("verifyCode");
        String verifyMail = (String) session.getAttribute("verifyEmail");
        if(emailCode == null || !emailCode.toLowerCase().equals(verifyCode.toLowerCase()) || !user.getEmail().equals(verifyMail)) {
            log.info("输入邮箱验证码{} 正确验证码 {}", emailCode, verifyCode);
            return new BaseResult(1, "邮箱验证码不正确");
        }
        BaseResult result = userService.register(user);

        if(result.get("code").equals("0")) {

            UsernamePasswordToken token = new UsernamePasswordToken(user.getEmail(), user.getPassword());
            SecurityUtils.getSubject().login(token);
        }
        log.info(result.toString());
        return result;

    }
}
